package com.leetcode.LC_MED;

public class LC98_2 {
    // 错误
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left, right;
        if (root.right != null) {
            right = root.val < maxVal(root.right);
        }
        if (root.left != null) {
            left = root.val > maxVal(root.left);
        }
        return root.val < maxVal(root.right) &&
                root.val > minVal(root.left) &&
                isValidBST(root.left) &&
                isValidBST(root.right);
    }

    public int maxVal(TreeNode root) {
        int max = root.val;
        if (root.left != null) {
            max = Math.max(max, maxVal(root.left));
        }
        if (root.right != null) {
            max = Math.max(max, maxVal(root.right));
        }
        return max;
    }

    public int minVal(TreeNode root) {
        int min = root.val;
        if (root.left != null) {
            min = Math.min(min, maxVal(root.left));
        }
        if (root.right != null) {
            min = Math.min(min, maxVal(root.right));
        }
        return min;
    }
}
